package com.wakyde.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    public String index(Model model){
        model.addAttribute("msg", "hello, shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(Model model){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(Model model){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(Model model){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        // 封装登录用户的数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        System.out.println(2);

        try {
            subject.login(token);
            System.out.println(3);

            return "redirect:/index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg", "用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg", "密码不正确");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, Model model){
        Subject subject = SecurityUtils.getSubject();

        subject.logout();

        model.addAttribute("msg","安全退出！");
        return "login";
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }
}
